package com.liuqianfei.markme.rules.inline;

import com.liuqianfei.markme.core.Token;
import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.Delimiter;
import com.liuqianfei.markme.rules.IAction;

import java.util.List;
import java.util.Stack;

/**
 * ~~strike through~~
 * @author liuqianfei
 */
public class StrikeThroughPostProcessAction implements IAction
{
    // Walk through delimiter list and replace text tokens with tags
    //
    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        Delimiter startDelim, endDelim;
        Token token;
        Stack<Integer> loneMarkers = new Stack<>();
        List<Delimiter> delimiters = state.getDelimiters();
        int max = state.getDelimiters().size();

        for (int i = 0; i < max; i++)
        {
            startDelim = delimiters.get(i);

            if (startDelim.marker != 0x7E/* ~ */)
                continue;

            if (startDelim.end == -1)
                continue;

            endDelim = delimiters.get(startDelim.end);

            token         = state.getTokens().get(startDelim.token);
            token.type    = "s_open";
            token.tag     = "s";
            token.nesting = 1;
            token.markup  = "~~";
            token.content = "";

            token         = state.getTokens().get(endDelim.token);
            token.type    = "s_close";
            token.tag     = "s";
            token.nesting = -1;
            token.markup  = "~~";
            token.content = "";

            if ("text".equals(state.getTokens().get(endDelim.token - 1).type)
                    && "~".equals(state.getTokens().get(endDelim.token - 1).content))
                loneMarkers.push(endDelim.token - 1);
        }

        // If a marker sequence has an odd number of characters, it's splitted
        // like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the
        // start of the sequence.
        //
        // So, we have to move all those markers after subsequent s_close tags.
        //
        while (loneMarkers.size() > 0)
        {
            int i = loneMarkers.pop();
            int j = i + 1;

            while (j < state.getTokens().size() && "s_close".equals(state.getTokens().get(j).type))
                j++;

            j--;

            if (i != j)
            {
                token = state.getTokens().get(j);
                Token tokeni = state.getTokens().get(i);
                state.getTokens().set(j, tokeni);
                state.getTokens().set(i, token);
            }
        }

        // FIXME I add it
        return true;
    }
}
